//const KEYWORD_MATCH = /^(.*浏览).*(\d+爆竹)$/;
const KEYWORD_MATCH = /^(浏览).*\d+s.*\d+(金币)$/;
const TIME_BROWES = 10000; // 浏览时间
const TIME_WAIT = 1000; // 界面切换等待的时间
const TIME_OUT = 30; // 超时时间
// 任务类型
const TASK_TYPE = {
  Browse: 1, // 浏览
  BrowseForWhile: 2, // 浏览一段时间
  ReturnTwoTimes: 3, // 需要2次返回才能退出的界面
  Shopping: 4, // 下单
};

let timerThread;  // 计时器线程
let timeout = 0;  // 计数

main();

function main() {
  auto.waitFor();
  //launchActivity();

  stayTimer();

  while (true) {
    checkTimeout();
    viewTask();
  }
}

function launchActivity() {
  sleep(TIME_WAIT);

  app.startActivity({
    action: "View",
    packageName: "com.tencent.mm",
    className: "com.tencent.mm.plugin.appbrand.ui.AppBrandUI"
  });
}

function stayTimer() {
  timerThread = threads.start(function () {
    setInterval(function () { timeout++; }, 1000);
  });
  sleep(TIME_WAIT);
}

function checkTimeout() {
  if (timeout > TIME_OUT) {
    timerThread.interrupt();
    log("停留某个页面超过30s, 退出脚本");
    exit();
  }
}

function viewTask() {
  if (textMatches(KEYWORD_MATCH).exists()) {
    sleep(TIME_WAIT);
    let widgets = textMatches(KEYWORD_MATCH).find();
    for (let index = 0; index < widgets.length; index++) {
      let widget = widgets[index];
      let indexInParent = widget.indexInParent();
      let widgetParent = widget.parent();
      let taskname = widgetParent.child(indexInParent - 2).text();
      let progress = widgetParent.child(indexInParent - 1).text();
      let describe = widgetParent.child(indexInParent).text();
      let num = parseInt(progress.match(/\d+(?=\/)/g));
      let total = parseInt(progress.match(/\d+(?=\))/g));
      //log(taskname + " " + num + "/" + total + " " + describe);

      if (num < total) {
        let taskType = checkTaskType(progress, describe);

        // 忽略一些任务
        if (taskType == TASK_TYPE.Shopping) {
          continue;
        }

        let buttonWidget = widgetParent.child(indexInParent + 1);
        if (buttonWidget.click()) {
          timeout = 0;
          log("正在进行任务:" + taskname + " " + (num + 1) + "/" + total + " " + describe);
          sleep(TIME_WAIT);

          if (taskType == TASK_TYPE.Browse) {
            returnNow();
          } else if (taskType == TASK_TYPE.BrowseForWhile) {
            returnLater();
          } else if (taskType == TASK_TYPE.ReturnTwoTimes) {
            returnTwoTimes();
          } else {
            returnNow();
          }
        }
      }
      sleep(TIME_WAIT);
    }
  }
}

function checkTaskType(taskname, describe) {
  let taskType = TASK_TYPE.BrowseForWhile;
  if (/下单/.test(taskname)) {
    taskType = TASK_TYPE.Shopping;
  }
  return taskType;
}

function returnNow() {
  sleep(TIME_WAIT);
  back();
}

function returnTwoTimes() {
  sleep(TIME_BROWES);
  back();
  sleep(TIME_WAIT);
  back();
}

function returnLater() {
  sleep(TIME_BROWES);
  back();
}
